#define  _CRT_SECURE_NO_WARNINGS 1
#include"slist.h"


void SLTprint(SLTNode* phead)
{
	SLTNode* cur = phead;
	while (cur)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}


SLTNode* BuyTNode(SLTDatatype  x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}





void SLTPushFront(SLTNode** pphead, SLTDatatype x)
{
	SLTNode* newnode = BuyTNode(x);
	newnode->next = *pphead;
	*pphead = newnode;

}


void SLTPushBack(SLTNode** pphead, SLTDatatype x)
{
	SLTNode* newnode = BuyTNode(x);
	SLTNode* tail = *pphead;
	while (tail->next)
	{
		tail = tail->next;
	}
	tail->next = newnode;
}



void SLTPopFront(SLTNode** pphead)
{

	SLTNode* tail = *pphead;
	*pphead = tail->next;
	free(tail);
	tail = NULL;
}



void SLTPopBack(SLTNode** pphead)
{
	SLTNode* tail = *pphead;
	while (tail->next->next)
	{   
		tail = tail->next;
	}
	free(tail->next);
	tail->next = NULL;
}



SLTNode* STFind(SLTNode* plist, SLTDatatype x)
{
	SLTNode* cur = plist;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void SLInsert(SLTNode** pphead, SLTNode* pos, SLTDatatype x)
{
	assert(pphead);
	assert(pos);
	if (*pphead == pos)
	{
		SLTPushFront(pphead, x);
	}
	else{
		SLTNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		SLTNode* newnode = BuyTNode(x);
		prev->next = newnode;
		newnode->next = pos;
	}
}


void SLInsertAfter(SLTNode* pos, SLTDatatype x)
{
	assert(pos);
	SLTNode* newnode = BuyTNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}


void SLErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead);
	assert(pos);
	if (pos == NULL)
	{
		SLTPopFront(pphead);
	}
	else
	{
		SLTNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);

	}
}




void SLEraseAfter(SLTNode* pos)
{
	assert(pos);
	assert(pos->next);
	SLTNode* next = pos->next;
	pos->next = next->next;
	free(next);
}